<template>
	<main-content
		:tableHeight.sync="tableHeight"
	>
		<template slot="query">
			<el-form ref="formRef" :inline="true" :model="queryData">
				<el-form-item label="总代账号：">
					<el-input
						v-model="queryData.proxyName"
						clearable
						size="medium"
						style="width: 200px"
						:placeholder="'留空为选择全部'"
					></el-input>
				</el-form-item>
				<el-form-item
					label="账单周期："
				>
					<el-select
						v-model="queryData.billEndDate"
						:placeholder="$t('common.select_all')"
						style="width:250px"
						:popper-append-to-body="false"
					>
						<el-option
							v-for="item in billDateList"
							:key="item.code"
							:label="item.description"
							:value="item.code"
						></el-option>
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-button
						type="primary"
						icon="el-icon-search"
						size="medium"
						@click="search"
					>
						{{ $t('common.search') }}
					</el-button>
					<el-button
						icon="el-icon-refresh-left"
						size="medium"
						@click="reset"
					>
						{{ $t('common.reset') }}
					</el-button>
					<el-button
						v-if="hasPermission('701031')"
						type="warning"
						icon="el-icon-download"
						size="medium"
						:loading="exportBtnLoading"
						@click="handleExportExcel"
					>
						{{ $t('common.export') }}
					</el-button>
					<!-- <el-button
						type="success"
						icon="el-icon-sort"
						:disabled="loading"
						size="medium"
						@click="openColSettings"
					>
						{{ $t('common.row_set') }}
					</el-button> -->
				</el-form-item>
			</el-form>
		</template>
		<template slot="content">
			<el-table
				v-loading="loading"
				ref="elTable"
				element-loading-spinner="el-icon-loading"
				border
				size="mini"
				class="small-size-table"
				:max-height="tableHeight"
				:data="tableData"
				style="width: 100%"
				show-summary
				:summary-method="(val) => handleRow(val, totalSummary)"
				:header-cell-style="getRowClass"
				highlight-current-row
			>
				<el-table-column
					v-for="(parent, parentI) in columns"
					:key="parentI"
					:label="parent.label"
					:minWidth="parent.minWidth"
					:prop="parent.prop"
					align="center"
				>
					<template v-if="parent.defaultSlot" slot-scope="scope">
						{{ parent.defaultSlot(scope) }}
					</template>
					<template v-if="parent.list">
						<el-table-column
							v-for="(item, index) in parent.list"
							:key="`column_${parentI}_${index}`"
							:prop="parent.list[index].prop"
							:align="item.alignCenter"
							:label="item.label"
							:min-width="item.minWidth"
						>
						<template slot="header">
							<div class="d-f-c">
								{{ item.label }}
								<el-tooltip
									v-if="item.itemTipContent"
									class="item"
									effect="dark"
									:content="item.itemTipContent"
									placement="top-start"
								>
									<i class="el-icon-question"></i>
								</el-tooltip>
							</div>
						</template>
							<template v-if="item.defaultSlot" slot-scope="scope">
								{{ item.defaultSlot(scope) }}
							</template>
						</el-table-column>
					</template>
				</el-table-column>
			</el-table>
			<!-- 分页 -->
			<el-pagination
				v-show="!!total"
				class="pageValue"
				:current-page.sync="pageNum"
				background
				layout="total, sizes,prev, pager, next, jumper"
				:page-size.sync="pageSize"
				:page-sizes="pageSizes"
				:total="total"
				:pager-count="9"
				@current-change="handleCurrentChange"
				@size-change="handleSizeChange"
			></el-pagination>
		</template>

		<el-dialog
			:title="$t('common.row_set')"
			center
			:visible.sync="colSettings.visible"
			width="475px"
			class="setting-div"
		>
			<div>
				<el-link type="primary" class="mb15" @click="clickDel">
					复原缺省
				</el-link>
			</div>
			<div
				v-for="(value, name1) in activityListField"
				:key="name1"
				class="setting-div"
			>
				<el-checkbox v-model="dialogColumnData[name1]">
					{{ name1 }}
				</el-checkbox>
			</div>
			<div slot="footer" class="dialog-footer">
				<el-button @click="colSettings.visible = false">
					{{ $t('common.cancel') }}
				</el-button>
				<el-button type="primary" @click="handleOrderList">
					{{ $t('common.submit') }}
				</el-button>
			</div>
		</el-dialog>
	</main-content>
</template>

<script>
import list from '@/mixins/list'
import dayjs from 'dayjs'
import { routerNames } from '@/utils/consts'
import summaryList from './components/summaryList'
import { getColumns } from './components/columns'
import MainContent from '@/components/MainContent/index.vue'

const setSearchTime = () => [
	dayjs()
		.startOf('day')
		.valueOf(),
	dayjs()
		.endOf('day')
		.valueOf()
]
export default {
	name: routerNames.agentBill,
	components: {
		MainContent
	},
	mixins: [list, summaryList],
	data() {
		return {
			tableHeight: 480,
			exportBtnLoading: false,
			queryData: {
				proxyName: undefined,
				billEndDate: undefined
			},
			billDateList: [],
			searchTime: setSearchTime(),
			colSettings: {
				visible: false,
				dialogColumnData: {}
			},
			tableData: [],
			totalSummary: {},
			oldCol: [],
			activityListField: {
				[this.$t('agent.bill_cycle_statrt_date')]: true,
				[this.$t('agent.bill_proxy_name')]: true,
				[this.$t('agent.bill_ty_valid_bet_amount')]: true,
				[this.$t('agent.bill_zr_valid_bet_amount')]: true,
				[this.$t('agent.bill_other_net_amount')]: true,
				[this.$t('agent.bill_rebate_amount')]: true,
				[this.$t('agent.bill_net_profit_amount')]: true,
				[this.$t('agent.bill_platform_zhangcheng_rate')]: true,
				[this.$t('agent.bill_account_adjustment_amount')]: true,
				[this.$t('agent.bill_platform_up_amount')]: true,
				[this.$t('agent.bill_platform_down_amount')]: true,
				[this.$t('agent.bill_last_period_balance_amount')]: true,
				[this.$t('agent.bill_platform_should_receipt_amount')]: true,
				[this.$t('agent.bill_platform_should_payment_amount')]: true,
				[this.$t('agent.bill_dx_amount')]: true
			}
		}
	},
	computed: {
		columns() {
			return getColumns(this)
		}
	},
	created() {
		this.getSettlementBillTimeList()
		this.initIndexDB('agentManageBill', this.activityListField)
	},
	methods: {
		getSettlementBillTimeList() {
			this.loading = true
			const params = {
				pageNum: 1,
				pageSize: 200,
			}
			this.$api
				.getBillPeriodQueryBillPeriod(params)
				.then((res) => {
					this.loading = false
					if (res?.code === 200) {
						const { record } = res?.data
						if (record.length > 0) {
							this.billDateList = record.map((item, index) => {
								const startTime = dayjs(
									String(item.periodStDate)
								).format('YYYYMMDD')
								const endTime = dayjs(
									String(item.periodEnDate)
								).format('YYYYMMDD')
								return {
									code: `${startTime}-${endTime}`,
									description: `${
										dayjs(
									String(item.periodStDate)
								).format('YYYY-MM-DD')
									} 至 ${dayjs(
									String(item.periodEnDate)
								).format('YYYY-MM-DD')}`
								}
							})
							this.queryData.billEndDate = this.billDateList[0].code
							this.loadBillData()
						}
					}
				})
				.catch(() => {
					this.loading = false
				})
		},
		amount(val) {
			return this.handleNumber('CNY', val)
		},
		handleShortcutBtnClick(val) {
			this.searchTime = val
			this.search()
		},
		elementToCheck(str) {
			if (this.elementToCheckList.includes(str)) {
				return true
			} else {
				return false
			}
		},
		getParams() {
			const [cycleStatrtDate, cycleEndDate] = this.queryData.billEndDate ? this.queryData.billEndDate.split('-') : []
			const params = {
				...this.queryData,
				...this.pageParams,
				cycleStatrtDate: cycleStatrtDate ? parseInt(cycleStatrtDate) : undefined,
				cycleEndDate: cycleEndDate ? parseInt(cycleEndDate) : undefined
				// billType: 2
			}
			delete params.billEndDate
			return params
		},
		loadBillData() {
			this.loading = true
			this.$api
					.getTopProxyBillList(this.getParams())
					.then((res) => {
						this.loading = false
						if (res.code === 200) {
							this.tableData = []
							this.tableData = res?.data?.record || []
							this.total = res?.data?.totalRecord || 0
							this.totalSummary = res?.data?.summary || {}
						}
					})
					.catch(() => {
						this.loading = false
					})
		},
		customSortOrder(data, sortOrder) {
			const sortedData = data.sort((a, b) => {
				const indexA = sortOrder.indexOf(a.venueName)
				const indexB = sortOrder.indexOf(b.venueName)
				return indexA - indexB
			})
			return sortedData
		},
		selectAllVenueMethod() {
			if (this.selectAllVenue) {
				this.queryData.venueCodes = []
				for (const item of this.venueNameList) {
					this.queryData.venueCodes.push(item.gameCode)
				}
			} else {
				this.queryData.venueCodes = []
			}
		},
		// 改变列表条数
		handleSizeChange(value) {
			this.pageNum = 1
			this.pageSize = value
			this.loadBillData()
		},
		handleCurrentChange(value) {
			this.pageNum = value
			this.loadBillData()
		},
		search() {
			this.pageNum = 1
			this.loadBillData()
		},
		changeBetDetailTableSort({ column, prop, order }) {
			this.betDetailQueryData.orderKey = prop
			if (order === 'ascending') {
				// 升序
				this.betDetailQueryData.orderType = 'asc'
			} else if (column.order === 'descending') {
				// 降序
				this.betDetailQueryData.orderType = 'desc'
			} else {
				delete this.betDetailQueryData.orderKey
				delete this.betDetailQueryData.orderType
			}
			this.getBetDetailData()
		},
		handleCurrentChangeDialog(val) {
			this.page = val
			this.getBetDetailData()
		},
		handleSizeChangeDialog(val) {
			this.page = 1
			this.size = val
			this.getBetDetailData()
		},
		reset() {
			this.pageNum = 1
			this.queryData.proxyName = undefined
			this.queryData.billEndDate = this.billDateList ? this.billDateList[0].code : undefined
			this.loadBillData()
		},
		handleExportExcel() {
			const params = this.getParams()
			this.exportBtnLoading = true
			this.exportExcelPublic({
				api: 'exportTopProxyBillList',
				params
			}).finally(() => {
				this.exportBtnLoading = false
			})
		},
		// 提交列设置数据
		handleOrderList() {
			this.colSettings.visible = false
			this.updateIndexDB()
		},
		// 打开列设置弹框
		openColSettings() {
			this.getIndexDB(this.activityListField)
			this.colSettings.visible = true
		},
		// 复原缺省
		clickDel() {
			for (const key in this.dialogColumnData) {
				this.dialogColumnData[key] = true
			}
		}
	}
}
</script>

<style lang="scss" scoped>
.tips-box {
	position: absolute;
	right: 10px;
	top: 50%;
	margin-top: -12px;
}

.d-f-c{
	display: flex;
	align-items: center;
	justify-content: center;
}

::v-deep .el-dialog__header {
	color: #909399;
	font-weight: 700;
}

::v-deep .el-table__fixed-footer-wrapper .cell,
::v-deep .el-table__footer-wrapper .cell {
	height: 100%;
	padding: 0 !important;
	margin: 0 !important;

	> div {
		height: 100%;
	}
}

::v-deep .footer_count_row {
	min-height: 50px;
	height: 50%;
	display: flex;
	font-weight: 700;
	padding: 5px 0;
	align-items: center;
	flex-direction: column;
	justify-content: center;
}

::v-deep .footer_count_row_border {
	border-top: 1px solid #ebeef5;
}
::v-deep .is-group th:not(:first-child) {
	background-color: #f5f7fa !important;
}
::v-deep .el-icon-question:after {
	font-size: 16px;
	margin-left: 0;
}

.fenye {
	text-align: center;
}
</style>
